class_name HealthComponent
extends Node

signal on_unit_hit()
signal on_unit_die()
signal on_health_changed(current_health: float, max_health: float)

var current_health := 1.0
var max_health := 1.0

func setup(stats: UnitStats) -> void:
	max_health = stats.health
	current_health = max_health
	on_health_changed.emit(current_health, max_health)
	
func take_damage(value: float) -> void:
	if is_died():
		return
		
	current_health = max(current_health - value, 0)
	
	on_unit_hit.emit()
	on_health_changed.emit(current_health, max_health)
	
	if current_health <= 0:
		on_unit_die.emit()
		die()
		
func die() -> void:
	owner.queue_free()

func is_died() -> bool:
	return current_health <= 0

func heal(amount: float) -> void:
	if is_died():
		return
	
	current_health = min(current_health + amount, max_health)
	on_health_changed.emit(current_health, max_health)
